from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.



class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone = models.CharField(max_length=20, default='', blank=True)
    qqnum = models.CharField(max_length=20, default='', blank=True)
    weixin = models.CharField(max_length=50, default='', blank=True)
    avatar = models.ImageField(upload_to='avatar/%Y/%m/%d', default=u'avatar/default.png', max_length=255)

    def __str__(self):
        return self.user.username

    class Meta:
        db_table = 'userprofile'
        ordering = ['-id']
        verbose_name = '用户信息'
        verbose_name_plural = '用户信息'


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.userprofile.save()